import React, { useMemo, useEffect, useImperativeHandle, useRef } from "react"
import { createPortal } from "react-dom"

interface PortalProps {
    attach?: HTMLElement | string
    children: React.ReactNode
}

export function getAttach(attach: PortalProps['attach']) {
    if (typeof attach === 'string') {
        return document.querySelector(attach)
    }
    if (typeof attach === 'object' && attach instanceof HTMLElement) {
        return attach
    }
    return document.body
}

const Portal = React.forwardRef((props: PortalProps, ref) => {
    const {
        attach = document.body,
        children
    } = props

    const container = useMemo(() => {
        const el = document.createElement('div')
        el.className = `portal-wrapper`
        return el
    }, [])

    useEffect(() => {
        const parentElement = getAttach(attach)
        parentElement?.appendChild(container)
        return () => {
            parentElement?.removeChild(container)
        };
    }, [attach, children]);

    useImperativeHandle(
        ref,
        () => container,
    )

    return createPortal(children, container)
})

export function TestPortal() {
    const containerRef = useRef<HTMLElement>(null);
    const content = <div className="btn">
        <button>按钮</button>
    </div>;

    useEffect(() => {
        console.log(containerRef);
    }, []);
    
    return <Portal attach={document.body} ref={containerRef}>
        {content}
    </Portal>
}